﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SharpTeam.Crm.SkypeDialer.Configuration;
using System.Net;
using System.Web.Services.Protocols;

namespace SharpTeam.Crm.SkypeDialer.ConfigurationManager
{
    public partial class ConfigurationForm : Form
    {
        private ICredentials _credentials;
        private string _serverUrl;

        public ConfigurationForm()
        {
            InitializeComponent();

            dt_organization.RowChanged += dt_organization_RowChanged;
            dt_organization.ColumnChanged += dt_organization_ColumnChanged;
        }

        private void dt_organization_ColumnChanged(object sender, DataColumnChangeEventArgs e)
        {
            // Выделена ли хотя бы одна строка?
            CheckIfRowsSelected();
        }

        void dt_organization_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            // Выделена ли хотя бы одна строка?
            CheckIfRowsSelected();
        }

        private void CheckIfRowsSelected()
        {
            bool selected = dt_organization.Rows.Cast<DataRow>().Aggregate(false, (current, row) => current | (bool)row[dc_selected]);

            bn_custom_standard.Enabled = selected;
        }

        private void ConfigurationForm_Load(object sender, EventArgs e)
        {
            // Запрашиваем урл сервера и креденшиалзы
            LoginForm loginForm = new LoginForm();

            if (loginForm.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
                this.Close();
            else
            {
                _credentials = loginForm.Credentials;
                _serverUrl = loginForm.ServerUrl;
                // Если все ок, заполняем грид именами организаций
                FillOrganizationGrid(CrmConnection.GetOrganizations(_credentials, _serverUrl));
                dataGridView1.Focus();
            }

        }

        /// <summary>
        /// Заполняем таблицу организаций данными
        /// </summary>
        /// <param name="orgname">Массив имен организаций</param>
        private void FillOrganizationGrid(IEnumerable<string> orgname)
        {
            foreach (var s in orgname)
            {
                DataRow row = dt_organization.NewRow();
                row[dc_name] = s;
                dt_organization.Rows.Add(row);
            }
        }


        private void bn_selectall_Click(object sender, EventArgs e)
        {
            // Все ли строки выделены?
            bool allselected = dt_organization.Rows.Cast<DataRow>().Aggregate(true, (current, row) => current & (bool)row[dc_selected]);

            // Выделяем/ снимаем выделение для всех строк
            foreach (DataRow row in dt_organization.Rows)
            {
                row[dc_selected] = !allselected;
            }

            // Снимаем фокус с кнопки
            dataGridView1.Focus();
        }

        private void bn_exit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void bn_custom_standard_Click(object sender, EventArgs e)
        {
            foreach (DataRow row in dt_organization.Rows)
            {
                // Если организация выбрана
                if ((bool)row[dc_selected])
                {
                    try
                    {
                        DialButtonsCreator buttonsCreator = new DialButtonsCreator((string) row[dc_name], _credentials,
                                                                                   _serverUrl);
                        buttonsCreator.CreateStandardButtons();
                        buttonsCreator.Commit();

                        row[dc_actionresult] = String.Format("Operation succeeded");

                    }
                    catch(SoapException ex)
                    {
                        row[dc_actionresult] = String.Format("Error: {0}. {1}", ex.Message, ex.Detail.InnerText);
                    }
                }
            }
        }
    }
}
